//
//  CommodityInFoViewController.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/4/21.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "CommodityInFoViewController.h"
#import "CommodityInfoHeadView.h"
#import "CommodityINfoTableViewCell.h"
#import "ShoppingZheKou_TableViewCell.h"
#import "Shopping_Cart_ViewController.h"
#import "SDCycleScrollView.h"
#import "AddShoppingView.h"
#import "UIViewAdditions.h"
#import "Buy_TableViewCell.h"
#import "CommodityInfoView.h"
#import "InterFace.h"
#import "CommodityListViewController.h"
#import "AlertView.h"
#import "InformationButton.h"
#import "BindingViewController.h"
#import "ProductInfoModel.h"
#import "ProductListModel.h"
#import "AFNetworking.h"
#import "EncryptionData.h"
#import "InfoViewController.h"
#import "UIImageView+WebCache.h"

#import "GMDCircleLoader.h"
#import "buyInfoView.h"

#import "CertificationViewController.h"
@interface CommodityInFoViewController ()<UITextFieldDelegate,Buy_TableViewCellDelegate,ProductInfoModelDelegate,UIAlertViewDelegate>
{
    UIView  *_alertBackview;
    AlertView *_alerView;
    AddShoppingView *_addView;
    UITextField *_number;
    UILabel *_weishangpracc;
    UITapGestureRecognizer *_singleTap;
    buyInfoView *_footView;
    UIAlertView *_alertShow;
}

@property (nonatomic, strong) NSMutableArray *productInfoArr;
@property (nonatomic, strong) ProductInfoModel *infoModel;
@end

@implementation CommodityInFoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem setHidesBackButton:YES];
    self.productInfoArr = [NSMutableArray array];
    
    self.infoModel= [[ProductInfoModel alloc] init];
    _infoModel.productInfoModelDelegate = self;
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSMutableDictionary *parameterDic = [NSMutableDictionary dictionary];
    parameterDic[@"ProductID"] = self.productlistModel.ProductID;
    parameterDic[@"AgentID"] = agentId;
    [_infoModel getProductInfo:self.productInfoArr parameter:parameterDic];
    
    
    [self createBackButton];
    [self createCosmeticTableView];
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
   
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:_singleTap];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

#pragma -mark 创建化妆品TableView
- (void)createCosmeticTableView{
    self.commodityInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.commodityInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.commodityInfoTableView.delegate = self;
    self.commodityInfoTableView.dataSource = self;

    [self.view addSubview:self.commodityInfoTableView];
    
    UIButton *boyButton = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-50, SCREEN_WIDTH, 50)];
    [boyButton setBackgroundImage:[UIImage imageNamed:@"商品详情_02"] forState:UIControlStateNormal];
    [boyButton addTarget:self action:@selector(buyClicka:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:boyButton];
}

#pragma mark 点击加入购物车
- (void)buyClicka:(UIButton *)sender{
    NSString *IsPayOffDeposit = [[NSUserDefaults standardUserDefaults] objectForKey:@"IsPayOffDeposit"];
  
    if ([IsPayOffDeposit isEqualToString:@"0"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您还没有缴纳保证金" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

    if (_number.text.integerValue== 0 || _number.text == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"商品数目不能为0" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
          sender.userInteractionEnabled = NO;
        [self addProductForCar:(UIButton *)sender];
    }
}
#pragma -mmark 创建返回按钮
-(void)createBackButton{
    
    UIView *qview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    UIButton *backBut = [UIButton buttonWithType:UIButtonTypeCustom];
    backBut.frame = CGRectMake(-25, -2, 85, 44);
    
    [backBut setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backBut addTarget:self action:@selector(backClick23) forControlEvents:UIControlEventTouchUpInside];
    [qview addSubview:backBut];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-110, 5, 200, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    title.text = @"商品详情";
    title.textColor = [UIColor whiteColor];
    [qview addSubview:title];
    self.navigationItem.titleView = qview;
    
    InformationButton *infonmationBut = [[InformationButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50, 0, 44, 44)];
    infonmationBut.informationNum.text = @"20";
    [infonmationBut addTarget:self action:@selector(goINfoVC) forControlEvents:UIControlEventTouchUpInside];
    [infonmationBut setImage:[UIImage imageNamed:@"查看库存_03"] forState:UIControlStateNormal];
    [qview addSubview:infonmationBut];
}

- (void)goINfoVC{

    InfoViewController *infomation =[[InfoViewController alloc] init];
    [self.navigationController pushViewController:infomation animated:YES];
}
#pragma -mark 获取商品详情接口结束代理方法
- (void)getProDuctInfoInterfaceEnd{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    self.commodityInfoTableView.tableHeaderView = [self createTableViewHeadView:self.infoModel.ThumbPathList];
    self.commodityInfoTableView.tableFooterView = [self crateFoodView];
    self.commodityInfoTableView.backgroundColor = LineColor;
    [self.commodityInfoTableView reloadData];
 
}
#pragma -mark //请求服务器繁华的错误信息代理
- (void)getrequesterror:(NSString *)error{
     [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:error delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
}
#pragma -mark 网络异常代理／服务器起错误代理
- (void)requesterror{
     [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}


#pragma -mark 点击返回按钮事件
- (void)backClick23{
    
    UIViewController *cV = self.commVC;
    cV.hidesBottomBarWhenPushed = NO;
   
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma -mark 创建tableview的headview
-(UIView *)createTableViewHeadView:(NSArray *)arr{
    

    
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*(SCREEN_WIDTH/720)+90)];
    // 本地加载 --- 创建不带标题的图片轮播器
//    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, myView.frame.size.height-98) imagesGroup:images];
    myView.backgroundColor = [UIColor whiteColor];
    NSMutableArray *nsUrls = [NSMutableArray array];
    for (NSString * url in arr) {
        
        NSURL *nsUrl = [NSURL URLWithString:url];
        [nsUrls addObject:nsUrl];
        
    }
    
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*(SCREEN_WIDTH/720))];
    [image sd_setImageWithURL:[NSURL URLWithString:[arr firstObject]]];
    
    [myView addSubview:image];
    
//    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, myView.frame.size.height-98) imageURLsGroup:nsUrls];
//
//    cycleScrollView.delegate = self;
//    cycleScrollView.dotColor = [UIColor colorWithRed:230/255.0 green:8/255.0 blue:88/255.0 alpha:1]; // 自定义分页控件小圆标颜色
//    [myView addSubview:cycleScrollView];
//    
//    //         --- 轮播时间间隔，默认1.0秒，可自定义
//    cycleScrollView.autoScrollTimeInterval = 3.0;
    
    //添加商品按钮
//    _addView = (AddShoppingView*)[[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:5];
//    [_addView setProductInfoData:self.infoModel];
//    _addView.frame = CGRectMake(0, image.bottom, SCREEN_WIDTH, 98);
//    [myView addSubview:_addView];
    
//    [NSString stringWithFormat:@"¥%.1f",self.infoModel.OriginaPrice.floatValue]
    
    UILabel *praceName = [[UILabel alloc] initWithFrame:CGRectMake(10, image.bottom+10, SCREEN_WIDTH, 21)];
    praceName.font = [UIFont fontWithName:nil size:15];
    praceName.text = self.infoModel.ProductName;
    [myView addSubview:praceName];
    
    UILabel *pracc = [[UILabel alloc] initWithFrame:CGRectMake(10, praceName.bottom+10, SCREEN_WIDTH/2, 21)];
    pracc.font = [UIFont fontWithName:nil size:15];
    pracc.text = [NSString stringWithFormat:@"¥%.1f",self.infoModel.OriginaPrice.floatValue];
    pracc.textColor = DaoHangColor;
    [myView addSubview:pracc];
    
    UILabel *pracc1 = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-10-100-60, praceName.bottom+10, 100, 30)];
    pracc1.font = [UIFont fontWithName:nil size:15];
//    pracc1.backgroundColor = [UIColor greenColor];
    pracc1.text = @"输入商品数目:";
    pracc1.textColor = [UIColor blackColor];
    pracc1.textAlignment = NSTextAlignmentRight;
    [myView addSubview:pracc1];
    
    _number = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-70, praceName.bottom+10, 60, 30)];
    _number.textAlignment = NSTextAlignmentCenter;
    _number.layer.borderWidth = 1.0;
    _number.layer.borderColor = BackColor.CGColor;
    _number.font = [UIFont fontWithName:nil size:14];
    _number.delegate = self;
    _number.text = @"1";
    [myView addSubview:_number];
    
    return myView;
    
    
}


#pragma -mark 点击self.view的点击手势
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    [self.commodityInfoTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.view endEditing:YES];
    if (_number.text.length <=0||[_number.text isEqualToString:@"0"]) {
        _footView.praceNumber.text =  [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue];
    } else{
    int num = _number.text.intValue;
    _footView.praceNumber.text =  [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue *num];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{

    [textField resignFirstResponder];
     int num = textField.text.intValue;
      _footView.praceNumber.text =  [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue *num];

}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
   [self.commodityInfoTableView setContentOffset:CGPointMake(0, 80) animated:YES];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [self.commodityInfoTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    if (textField.text.length <=0||[_number.text isEqualToString:@"0"]) {
        _footView.praceNumber.text =  [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue];
    } else{
    [textField resignFirstResponder];
    int num = textField.text.intValue;
    _weishangpracc.text =  [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue *num];
    }
        return YES;
}
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isEqual:_number]) {
        NSMutableString *text = [textField.text mutableCopy];
        [text replaceCharactersInRange:range withString:string];
            return [text length] <= 5;
    }
    return YES;

}
#pragma -makr 设置电话号码输入框只能输入数字
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma -mark 创建提示框
- (void)createAlertView{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [window addSubview:_alertBackview];
    _alerView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:10];
    _alerView.frame = CGRectMake(50, SCREEN_HEIGHT/2.0-130/2.0, SCREEN_WIDTH-100, 130);
    [_alerView.confirmBut addTarget:self action:@selector(confirmButClick) forControlEvents:UIControlEventTouchUpInside];
    [_alerView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:_alerView];
}

#pragma -mark 点击提示框去绑定银行卡
- (void)confirmButClick{
    [_alertBackview removeFromSuperview];
      [_alerView removeFromSuperview];
//    BindingViewController *bindingVC = [[BindingViewController alloc] init];
//    [self.navigationController pushViewController:bindingVC animated:YES];
    CertificationViewController *offline = [[CertificationViewController alloc]init];//绑定状态
    offline.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:offline animated:YES];
}

#pragma -mark 点击提示框稍后按钮
- (void)cancelButClick{
    [_alertBackview removeFromSuperview];
    [_alerView removeFromSuperview];
    
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{

}

#pragma -mark TableViewHeadView点击代理事件
- (void)getBut:(id)but{
    NSLog(@"点击了图片");
}

#pragma -mark 创建tableView的Foodview
-(UIView *)crateFoodView{

    _footView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:11];
    _footView.frame =CGRectMake(0, 0, SCREEN_WIDTH, 54);
    _footView.praceNumber.text = [NSString stringWithFormat:@"¥%.1f",self.infoModel.DiscountPrice.floatValue];
    return _footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
//        return 64;
        return 0;
    } else if(indexPath.row == 1){
        return 0;
    }
        return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.productInfoArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *iden = @"sosmetic";
    ShoppingZheKou_TableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:iden];
    ;
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:6];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    static NSString *idenBuy = @"sosmeticBuy";
    Buy_TableViewCell *buycell =  [tableView dequeueReusableCellWithIdentifier:idenBuy];
  
    if (buycell == nil) {
        buycell = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:7];
    }
      buycell.selectionStyle = UITableViewCellSelectionStyleNone;
    buycell.delegate = self;
    
    if (indexPath.row == 0) {
    
        [cell setWeiShangPrice:self.infoModel];
        return cell;
    } else
        
        return buycell;
}

#pragma -mark Buy_TableViewCell代理方法
- (void)buyShopping:(id)sender{
    Shopping_Cart_ViewController *car = [self.navigationController.storyboard instantiateViewControllerWithIdentifier:@"ShoppingCar"];
    [self.navigationController pushViewController:car animated:YES];

}

#pragma -mark 响应服务器，把商品加入购物车
-(void)addProductForCar:(UIButton *)sender{
    @try {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameter = @{@"ProductID":self.infoModel.ProductID,@"AgentID":userId,@"Number":_number.text};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    NSString *str = [self encodeString:jsonString:PasswordKey];
    NSDictionary *paramer = @{@"sign":str};
    [manager POST:AddProductForCar parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        sender.userInteractionEnabled = YES;
        NSString *str = responseObject[@"sign"];
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        if ([[dataDic objectForKey:@"reason"] isEqualToString:@"您尚未绑定银行卡"]) {
            [self createAlertView];
            return;
        }
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
           [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
            _alertShow = [[UIAlertView alloc] initWithTitle:nil message:@"加入购物车成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [_alertShow show];
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          sender.userInteractionEnabled = YES;
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];
    }
    @catch (NSException *exception) {
        
        NSLog(@"商品详情页点击加入购物车抛出异常 ＝＝＝＝＝ %@",[exception userInfo]);
    }
    
}
#pragma mark － alert代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == _alertShow) {
        UIViewController *cV = self.commVC;
        cV.hidesBottomBarWhenPushed = NO;
         self.tabBarController.selectedIndex = 1;
        [self.navigationController popToRootViewControllerAnimated:NO];
    }
}
#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data :(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    return base64String1;
}

@end
